//
//  ZCAllTableViewController.m
//  ZCBaiSi
//
//  Created by zc on 16/7/22.
//  Copyright © 2016年 zc. All rights reserved.
//

#import "ZCAllTableViewController.h"
#import <AFNetworking.h>
#import "ZCTopic.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import "ZCRefreshHeader.h"
#import "ZCRefreshFooter.h"
#import <UIImageView+WebCache.h>
#import "ZCHttpSessionManager.h"
#import "ZCTopicCell.h"
@interface ZCAllTableViewController ()
//数据源
@property (nonatomic, strong) NSMutableArray<ZCTopic *> *topics;
//maxtime:用来加载下一页数据
@property (nonatomic, copy) NSString *maxtime;
@property (nonatomic, strong) ZCHttpSessionManager *manager;

@end
static NSString * const ZCTopicCellID  = @"topic";
@implementation ZCAllTableViewController

- (ZCHttpSessionManager *)manager{
    if (!_manager) {
        self.manager = [ZCHttpSessionManager manager];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self loadNewTopics];
    [self setupTabView];
    [self setupRefresh];
}

- (void)setupTabView{
    self.tableView.backgroundColor = ZCCommonBgColor;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 35, 0, 49, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZCTopicCell class]) bundle:nil] forCellReuseIdentifier:ZCTopicCellID];
}

- (void)setupRefresh{
    self.tableView.mj_header  = [ZCRefreshHeader headerWithRefreshingBlock:^{
        [self loadNewTopics];
    }];
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [ZCRefreshFooter footerWithRefreshingBlock:^{
        [self loadMoreTopics];
    }];
}

#pragma mark -- 数据加载
- (void)loadNewTopics{
    //取消其他请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];//相当于[self.manager invalidateSessionCancelingTasks:YES];关闭NSURLSession+取消所有请求
    
    //参数
    NSMutableDictionary *params =[@{@"a":@"list",@"c":@"data",@"type":@"1"}mutableCopy];
    
    [self.manager GET:ZCCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //存储maxtime 用来加载下一页数据
        self.maxtime = responseObject[@"info"][@"maxtime"];
        self.topics = [ZCTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.tableView reloadData];
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ZCLog(@"%ld",error.code);
        [self.tableView.mj_header endRefreshing];
    }];
}

//加载更多

- (void)loadMoreTopics{
    //取消所有的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];

    //参数
    NSMutableDictionary *params =[@{@"a":@"list",@"c":@"data",@"type":@"1"}mutableCopy];
    params[@"maxtime"] = self.maxtime;
    [self.manager GET:ZCCommonURL  parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //存储这页对应的maxtime 用来加载下一页数据
        self.maxtime = responseObject[@"info"][@"maxtime"];
        NSArray *moreTopics = [ZCTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.topics addObjectsFromArray:moreTopics];
//        for (NSUInteger i = 0; i< self.topics.count; i++) {
//            if (self.topics[i].top_cmt.count) {//有最热评论
//                 
//            }
//        }
        [self.tableView reloadData];
        //结束刷新
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ZCLog(@"%@",error);
        //error.code 错误编码
        if (error.code == NSURLErrorCancelled) {
            //取消了任务
        }else{
            //其他错误
        }
        [self.tableView.mj_footer endRefreshing];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.topics.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:ZCTopicCellID];
    cell.topic = self.topics[indexPath.row];
   
    
    // Configure the cell...
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //根据ZCTopic数据计算出cell的具体高度，并且返回 
    return self.topics[indexPath.row].cellHeight;
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
